package net.chenlin.dp.common.support.shiro;

import net.chenlin.dp.common.entity.Query;
import net.chenlin.dp.modules.sys.dao.SysMenuMapper;
import net.chenlin.dp.modules.sys.entity.SysMenuEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 产生责任链，确定每个url的访问权限
 * @author zcl<yczclcn@163.com>
 */
public class ShiroPermsFilterFactoryBean extends ShiroFilterFactoryBean {

	private static final Logger LOGGER = LoggerFactory.getLogger(ShiroPermsFilterFactoryBean.class);
	
	@Autowired
	private SysMenuMapper sysMenuMapper;

	/**
	 * 默认配置权限链
	 */
	public Map<String, String> defaultChainMap;

	/**
	 * constructor
	 */
	public ShiroPermsFilterFactoryBean() {
		defaultChainMap = new LinkedHashMap<>(16);
	}

	/**
	 * 初始化方法
	 * @return
	 */
	public Map<String, String> init() {
		defaultChainMap.clear();
		defaultChainMap.put("/favicon.ico", "anon");
		defaultChainMap.put("/statics/**", "anon");
		defaultChainMap.put("/error/**", "anon");
		defaultChainMap.put("/login.html", "anon");
		defaultChainMap.put("/sys/login", "anon");
		defaultChainMap.put("/sys/captcha.jpg", "anon");
		return defaultChainMap;
	}

	/**
	 * 增加数据库权限
	 * @param filterChainDefinitionMap
	 */
	@Override
	public void setFilterChainDefinitionMap(Map<String, String> filterChainDefinitionMap) {
		// 如果默认为空，为首次启动，则需要设置默认权限过滤策略
		if (filterChainDefinitionMap.isEmpty()) {
			filterChainDefinitionMap.putAll(init());
		}
		// 从菜单表中查询菜单配置
		List<SysMenuEntity> lists = sysMenuMapper.list(new Query());
		for(SysMenuEntity menu : lists) {
			String permKey = menu.getPerms();
			String permUrl = menu.getUrl();
			if(StringUtils.isNotEmpty(permKey) && StringUtils.isNotEmpty(permUrl)) {
				filterChainDefinitionMap.put(permUrl, "perms[" + permKey + "]");
			}
		}
		filterChainDefinitionMap.put("/**", "authc");
		super.setFilterChainDefinitionMap(filterChainDefinitionMap);
		LOGGER.info("init perms finished.");
	}

}
